#include "lectura.h"

int valida_posicion(SDL_Event event)
{
	if(event.button.x > GRID_POSX && event.button.x < (GRID_POSX + ANCHO_ITEM))
		if(event.button.y > GRID_POSY && event.button.y < (GRID_POSY + ANCHO_ITEM))
			return 1;
	return 0;
}

int obtener_posicion(SDL_Event event)
{
	int valx = (event.button.x - GRID_POSX)/ ANCHO_ITEM;
	int valy = (event.button.y - GRID_POSY)/ ANCHO_ITEM;
	
	switch(valy)
	{
		case 0:
			if(valx == 0) return 0;
			if(valx == 1) return 1;
			else          return 2;
			break;
			
		case 1:
			if(valx == 0) return 3;
			if(valx == 1) return 4;
			else          return 5;
			break;
			
		case 2:
			if(valx == 0) return 6;
			if(valx == 1) return 7;
			else          return 8;
			break;
	}
}

void* thread_lectura(void *nada)
{
	SDL_Event event;
	int ret = -1, done = 0;
	
	// Ignorar movimiento mouse
	SDL_EventState(SDL_MOUSEMOTION, SDL_IGNORE);
	
	while(!done)
	{
			// Espero por evento (espera activa = fix)
	    while(SDL_WaitEvent(&event))
	    {
	    	switch(event.type)
	    	{
					case SDL_KEYDOWN:
						done = 1;
					break;
					
					case SDL_MOUSEBUTTONDOWN:
						//SDL_GetMouseState(&dest.x,&dest.y);
						if(valida_posicion(event))
						{
							ret = obtener_posicion(event);
							
							switch(ret)
							{
								case 0:
									s_mov.posx = GRID_POSX;
									s_mov.posy = GRID_POSY;
									break;
									
								case 1:
									s_mov.posx = GRID_POSX + ANCHO_ITEM;
									s_mov.posy = GRID_POSY;
									break;
								
								case 2:
									s_mov.posx = GRID_POSX + 2*ANCHO_ITEM;
									s_mov.posy = GRID_POSY;
									break;
									
								case 3:
									s_mov.posx = GRID_POSX;
									s_mov.posy = GRID_POSY + ANCHO_ITEM;
									break;
									
								case 4:
									s_mov.posx = GRID_POSX + ANCHO_ITEM;
									s_mov.posy = GRID_POSY + ANCHO_ITEM;
									break;
									
								case 5:
									s_mov.posx = GRID_POSX + 2*ANCHO_ITEM;
									s_mov.posy = GRID_POSY + ANCHO_ITEM;
									break;
									
								case 6:
									s_mov.posx = GRID_POSX;
									s_mov.posy = GRID_POSY + 2*ANCHO_ITEM;
									break;
									
								case 7:
									s_mov.posx = GRID_POSX + ANCHO_ITEM;
									s_mov.posy = GRID_POSY + 2*ANCHO_ITEM;
									break;
									
								case 8:
									s_mov.posx = GRID_POSX + 2*ANCHO_ITEM;
									s_mov.posy = GRID_POSY + 2*ANCHO_ITEM;
									break;
							}
						
						printf("Boton %d presionado en (%d,%d)\n",event.button.button,event.button.x,event.button.y);
						
						// Mandar imagen circulo a pantalla
						if(event.button.button == SDL_BUTTON_LEFT)
							s_mov.status = ESFERA;
						else
							if(event.button.button == SDL_BUTTON_RIGHT)
								s_mov.status = CUBO;
						
						// Envío señal a pantalla para actualizar
						pthread_kill(tid_pantalla,SIGUSR1);
					}
					break;
				}
			}
	}
}
